<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <form @submit.prevent="saveEventConfig" id="event-config-form-sncheckin" class="config-form">
        <h2 class="form-title">事件配置 - SN_CheckIN</h2>

        <div class="form-section">
          <h3 class="form-section-title">基本设置</h3>
          <div class="form-group flex items-center gap-4 mb-3">
            <span class="toggle-label">启用此事件</span>
            <label class="switch">
              <input type="checkbox" id="sncheckin-enabled" v-model="eventConfig.enabled">
              <span class="slider" :class="{ 'checked': eventConfig.enabled }"></span>
            </label>
          </div>
          <p class="form-description mb-4">启用后，产品进站时将触发此事件进行核对。</p>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group col-span-2">
              <label for="sncheckin-url" class="form-label">接收 URL</label>
              <input type="url" id="sncheckin-url" v-model="eventConfig.url" class="form-input"
                     placeholder="例如: http://mes.example.com/api/checkin">
              <p class="form-description">MES 接收 SN_CheckIN 事件数据的 URL。</p>
            </div>

            <div class="form-group">
              <label for="sncheckin-token" class="form-label">认证 Token</label>
              <input type="text" id="sncheckin-token" v-model="eventConfig.Token" class="form-input"
                     placeholder="用于验证是否能调用该接口，需MES提供">
              <p class="form-description">用于接口认证。</p>
            </div>
            <div class="form-group">
              <label for="sncheckin-line" class="form-label">产线 (Line)</label>
              <input type="text" id="sncheckin-line" v-model="eventConfig.Line" class="form-input"
                     placeholder="请输入在产线文档中对应的产线编码">
              <p class="form-description">当前产线编码。</p>
            </div>
            <div class="form-group">
              <label for="sncheckin-stationid" class="form-label">站点 ID (StationID)</label>
              <input type="text" id="sncheckin-stationid" v-model="eventConfig.StationID" class="form-input"
                     placeholder="请输入在部门文档中对应的工站ID">
              <p class="form-description">工站程序ID（MES Station）。</p>
            </div>
            <div class="form-group">
              <label for="sncheckin-machineid" class="form-label">机台 ID (MachineID)</label>
              <input type="text" id="sncheckin-machineid" v-model="eventConfig.MachineID" class="form-input"
                     placeholder="请输入机台编号">
              <p class="form-description">机台编号。</p>
            </div>
            <div class="form-group">
              <label for="sncheckin-fixsn" class="form-label">固定 SN (FixSN)</label>
              <input type="text" id="sncheckin-fixsn" v-model="eventConfig.FixSN" class="form-input"
                     placeholder="请输入固定SN">
              <p class="form-description">固定SN。</p>
            </div>
          </div>
        </div>

        <!-- 动态数据部分 -->
        <div class="form-section">
          <h3 class="form-section-title">动态数据</h3>
          <p class="form-description mb-4">以下数据在进站时动态添加，仅用于测试</p>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group">
              <label for="test-sn" class="form-label">序列号 (SN)</label>
              <input type="text" id="test-sn" v-model="eventConfig.SN" class="form-input"
                     placeholder="产品序列号">
              <p class="form-description">产品序列号。</p>
            </div>
            <div class="form-group">
              <label for="test-carrierid" class="form-label">载具ID (CarrierID)</label>
              <input type="text" id="test-carrierid" v-model="eventConfig.CarrierID" class="form-input"
                     placeholder="载具ID">
              <p class="form-description">载具ID，用于载具相关功能。</p>
            </div>
            <div class="form-group">
              <label class="form-label">发送时间 (SendTime)</label>
              <input type="text" class="form-input" :value="getCurrentDateTime()" disabled>
              <p class="form-description">事件发送时间，格式：yyyy/MM/dd HH:mm:ss。</p>
            </div>
          </div>
        </div>

        <!-- 测试事件部分 -->
        <div class="form-section">
          <h3 class="form-section-title">事件测试</h3>

          <div class="mt-4">
            <!--            <button type="button" class="hmi-button hmi-button-primary"-->
            <!--                    @click="testCheckInEvent"-->
            <!--                    :disabled="isTesting">-->
            <!--              <i :class="isTesting ? 'fas fa-spinner fa-spin' : 'fas fa-paper-plane'"></i>-->
            <!--              {{ isTesting ? '测试中...' : '发送测试请求' }}-->
            <!--            </button>-->
          </div>

          <div v-if="testResult.show" class="mt-4 p-4 rounded-md text-sm"
               :class="{'bg-green-50 border border-green-200': testResult.success, 'bg-red-50 border border-red-200': !testResult.success}">
            <div class="font-semibold mb-2"
                 :class="{'text-green-700': testResult.success, 'text-red-700': !testResult.success}">
              {{ testResult.success ? '测试成功' : '测试失败' }}
            </div>
            <div class="text-gray-700 mb-2">{{ testResult.message }}</div>
            <pre v-if="testResult.data" class="bg-gray-100 p-2 rounded text-xs overflow-auto max-h-40">{{
                JSON.stringify(testResult.data, null, 2)
              }}</pre>
          </div>
        </div>

        <div class="button-group">
          <button type="button" id="btn-cancel-event-config" class="hmi-button hmi-button-secondary" @click="goBack">
            <i class="fas fa-times"></i>取消
          </button>
          <button type="submit" id="btn-save-event-config" class="hmi-button hmi-button-primary" :disabled="isSaving">
            <i :class="isSaving ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>{{
              isSaving ? '保存中...' : '保存配置'
            }}
          </button>
        </div>
      </form>
    </main>

    <div v-if="notification.show" id="notification" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error', 'show': notification.show }">
      <span id="notification-message">{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount} from 'vue'
import {useRouter} from 'vue-router'
import {getMesEventConfig, saveMesEventConfig} from '@/api/mesEvent';
// 导入MES事件服务
const eventName = 'SN_CheckIn'
const router = useRouter() // 获取路由实例
// --- 响应式数据 ---
// 事件配置数据
const eventConfig = reactive({
  "enabled": false,
  "url": '',
  "EventID": "SN_CHECKIN",
  "Line": "",
  "StationID": "",
  "MachineID": "",
  "OPID": "",
  "Token": "",
  "FixSN": "",
  "SN": "",
  "CarrierID": "",
  "SendTime": ""
})

// 用于跟踪表单是否有未保存的更改
const isSaving = ref(false) // 用于控制保存按钮的加载状态

// 通知状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success', // 'success' or 'error'
  timeoutId: null // 用于存储定时器ID
})

// 测试状态
const isTesting = ref(false)
const testResult = reactive({
  show: false,
  success: false,
  message: '',
  data: null
})

// --- 方法 ---

// 显示通知
const showNotification = (message, type = 'success') => {
  notification.show = true
  notification.message = message
  notification.type = type
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
  notification.timeoutId = setTimeout(() => {
    notification.show = false
  }, 3000)
}

// 获取当前日期时间格式化字符串，用于 SENDTIME
const getCurrentDateTime = () => {
  const now = new Date();
  return now.getFullYear() + '/' +
      String(now.getMonth() + 1).padStart(2, '0') + '/' +
      String(now.getDate()).padStart(2, '0') + ' ' +
      String(now.getHours()).padStart(2, '0') + ':' +
      String(now.getMinutes()).padStart(2, '0') + ':' +
      String(now.getSeconds()).padStart(2, '0');
}

// 加载事件配置
const loadEventConfig = () => {
  getMesEventConfig(eventName).then(data => {
    console.log(data)
    Object.assign(eventConfig, data)
  })
}

// 保存事件配置
const saveEventConfig = () => {
  isSaving.value = true // 显示保存中状态

  // 构建要保存的数据对象 (深拷贝)
  const dataToSave = JSON.parse(JSON.stringify(eventConfig))

  saveMesEventConfig(eventName, dataToSave).then(res => {
    goBack()
  })
}

// 导航回上一页，检查未保存更改 (通常是事件配置导航页)
const goBack = () => {
  router.back() // 使用 Vue Router 返回上一页
}

// 测试 SN_CheckIN 事件
const testCheckInEvent = async () => {
  // 清除之前的测试结果
  testResult.show = false

  try {
    isTesting.value = true

    // 构建事件数据
    const eventData = {
      // 固定配置部分
      EventID: eventConfig.EventID,
      Line: eventConfig.Line,
      StationID: eventConfig.StationID,
      MachineID: eventConfig.MachineID,
      OPID: eventConfig.OPID,
      Token: eventConfig.Token,
      FixSN: eventConfig.FixSN,

      // 动态数据部分
      SN: eventConfig.SN,
      CarrierID: eventConfig.CarrierID || '',
      SendTime: getCurrentDateTime()
    }

    // 发送 MES 事件
    const result = await sendMESEvent(EVENT_TYPES.SN_CHECKIN, eventData)

    // 处理成功响应
    testResult.success = true
    testResult.message = '事件发送成功，MES响应成功'
    testResult.data = result.data

  } catch (error) {
    console.error('测试SN_CheckIN事件失败:', error)
    // 处理错误响应
    testResult.success = false
    testResult.message = `错误: ${error.message || '未知错误'}`
    testResult.data = error.response ? error.response.data : null
  } finally {
    isTesting.value = false
    testResult.show = true
  }
}


// --- 生命周期钩子 ---
onMounted(() => {
  console.log('SN_CheckIN Event Config Page mounted')
  // 页面挂载后加载配置数据
  loadEventConfig()
})

onBeforeUnmount(() => {
  // 清理通知定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
})
</script>

<style scoped>
/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1.5rem;
  overflow-y: auto; /* Enable scrolling for form */
}

/* --- Configuration Form --- */
.config-form {
  background-color: var(--bg-secondary);
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
  padding: 1.5rem;
  border: 1px solid var(--border-color);
  max-width: 900px; /* Adjust max width for this form */
  margin: 0 auto; /* Center form */
}

.form-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  text-align: center;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.75rem;
}

.form-section {
  margin-bottom: 1.5rem;
}

.form-section-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.75rem;
  border-left: 3px solid var(--accent-blue);
  padding-left: 0.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.form-input, .form-select {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
  font-size: 0.875rem;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  background-color: #f9fafb;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
  background-color: white;
}

/* Removed validation styling */

.form-input[readonly] {
  background-color: #e5e7eb;
  cursor: not-allowed;
  opacity: 0.7;
  color: var(--text-secondary);
}

.form-select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3csvg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
}

.form-description {
  font-size: 0.7rem;
  color: var(--text-tertiary);
  margin-top: 0.25rem;
}

/* Input group for select + button (if any) */
.input-button-group {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.input-button-group .form-select {
  flex-grow: 1;
}

.input-button-group .hmi-button {
  flex-shrink: 0;
}


/* Toggle Switch */
.toggle-switch {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.toggle-label {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  flex-shrink: 0;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  flex-shrink: 0;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 14px;
  width: 14px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

/* Apply background color based on checked state in Vue with binding */
.slider.checked {
  background-color: var(--accent-blue);
}

/* Apply transform based on checked state in Vue with binding */
input:checked + .slider:before {
  transform: translateX(20px);
}


/* --- Buttons --- */
.button-group {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1.5rem;
}

.hmi-button {
  padding: 0.6rem 1.2rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

/* Adjusted padding for small button */
.hmi-button-small {
  padding: 0.35rem 0.7rem;
  font-size: 0.75rem;
}

.hmi-button i {
  font-size: 1em;
}

/* HMI Button Colors - Defined by variables */
.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* Specific hover color */
.hmi-button-secondary {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

/* Specific hover color */
.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* --- Notification --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  z-index: 100;
}

.notification.show {
  opacity: 1;
  visibility: visible;
}

/* Notification Colors - Defined by variables */
.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}
</style>
